package top.scsoul.voes.web.controller.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.scsoul.voes.common.core.domain.AjaxResult;
import top.scsoul.voes.framework.web.service.DataInitService;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/api/system")
public class SystemController {
    @Autowired
    DataInitService dataInitService;

    @RequestMapping("/reset")
    public AjaxResult result() {
        dataInitService.init();
        return AjaxResult.success();
    }

    @RequestMapping("/resetProgress")
    public AjaxResult resetProgress() {
        return AjaxResult.success(dataInitService.getProgress());
    }


    @RequestMapping("/picUpload")
    public AjaxResult picUpload(MultipartFile file) throws IOException {
        String trueFileName = null;

        if (file != null) {
            String path = null;// 文件路径
            String type = null;//文件类型
            String fileName = file.getOriginalFilename();// 文件原名
            assert fileName != null;
            type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = new ApplicationHome().getDir().getPath() + "/";
                    // 自定义的文件名称
                    trueFileName = System.currentTimeMillis() + fileName;
                    // 设置存放图片文件的路径
                    File uploadDir = new File(realPath + "upload");
                    if (!uploadDir.exists()) {
                        boolean mkdir = uploadDir.mkdir();
                    }
                    String notRealpath = "upload" + "/" + trueFileName;
                    path = realPath + notRealpath;
                    // 转存文件到指定的路径
                    file.transferTo(new File(path));
                    return AjaxResult.success(notRealpath);
                } else {
                    return AjaxResult.error("文件类型错误");
                }
            } else {
                return AjaxResult.error("文件类型为空");
            }
        } else {
            return AjaxResult.error("没有找到相对应的文件");
        }
    }

}
